package org.biubiu0002.baiblog.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.biubiu0002.baiblog.core.dao.MessageDao;
import org.biubiu0002.baiblog.core.model.entity.MessageEntity;
import org.biubiu0002.baiblog.core.service.MessageService;
import org.biubiu0002.baiblog.im.constants.MessageConstants;
import org.biubiu0002.baiblog.im.dto.message.Message;
import org.biubiu0002.baiblog.im.dto.message.MessageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Author: biubiu0002
 * @Date: 2022/10/25 12:30
 **/
@Service
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {

    @Resource
    private MessageDao messageDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void saveHistoryChatMsg(Message chatMsg) {
        MessageEntity messageEntity = assembleMessageEntity(chatMsg);
        this.save(messageEntity);
    }


    @Override
    public List<MessageEntity> getHistoryMsg(Long lastMsgId, String uid, String withUid, Integer type) {
        lastMsgId = lastMsgId!=null?lastMsgId: IdWorker.getId();
        List<MessageEntity> historyMsgList=new ArrayList<>();
        if(type.equals(MessageConstants.MessageCommandType.PRIVATE_MESSAGE)){
            historyMsgList = messageDao.getPrivateChatHistoryMsg(lastMsgId, uid, withUid);
        }
        else if(type.equals(MessageConstants.MessageCommandType.GROUP_MESSAGE)){
            historyMsgList = messageDao.getGroupChatHistoryMsg(lastMsgId, withUid);
        }
        if(CollectionUtils.isEmpty(historyMsgList)){
            return Collections.emptyList();
        }
        return historyMsgList;
    }

    private MessageEntity assembleMessageEntity(Message chatMsg)  {
        MessageRequest messageRequest = chatMsg.getMessageRequest();
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMsgId(messageRequest.getMsgId());
        messageEntity.setMsgContent(messageRequest.getContent());
        messageEntity.setFromUid(messageRequest.getFrom());
        messageEntity.setToUid(messageRequest.getTo());
        messageEntity.setFromNick(messageRequest.getFromNick());
        messageEntity.setMsgType(messageRequest.getType());
        Date date = new Date(messageRequest.getTime());
        messageEntity.setSendTime(date);
        return messageEntity;
    }


}
